import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:member_center_sdk/core/sdk_config.dart';
import 'package:member_center_sdk/core/sdk_core.dart';
import 'package:shared_preferences/shared_preferences.dart';

class MemberCenterSdk {
  static SdkCore _core;
  static bool _isInit = false;

  static Future setDeviceInfo(String deviceId, String deviceName) async {
    if (_core == null) {
      try {
        var jsonStr =
            await rootBundle.loadString("assets/configs/member_sdk.json");
        Map<String, dynamic> map = json.decode(jsonStr);
        if (map.containsKey("merchantId") &&
            map.containsKey("signKey") &&
            map.containsKey("host") &&
            map.containsKey("port")) {
          int merchantId = int.tryParse(map["merchantId"].toString());
          int port = int.tryParse(map["port"].toString());
          if (merchantId > 0 && port > 0) {
            String signKey = map["signKey"].toString();
            String host = map["host"].toString();
            var prefs = await SharedPreferences.getInstance();
            _core = SdkCore(
                SdkConfig()
                  ..host = host
                  ..signKey = signKey
                  ..merchantId = merchantId
                  ..port = port
                  ..deviceName = deviceName
                  ..deviceId = deviceId,
                prefs);
          } else {
            print("配置文件的商户Id错误,请检查");
          }
        } else {
          print("配置文件错误,请检查,不存在KEY");
        }
      } catch (ex) {
        print("配置文件错误,请检查");
        print(ex);
      }
    }
    _isInit = true;
  }

  static SdkCore get() {
    if (!_isInit) {
      print("未初始化,请调用setDeviceInfo");
    }
    return _core;
  }
}
